package edu.sctu.zhengsenwen.month201506.day20150628;

import java.io.*;

/**
 * Created by user15 on 2015/6/28.
 */
public class DirectoryAndTxt {

    File file = null;
    File file1 = null;
    File file2 = null;

    HttpRequest httpRequest = new HttpRequest();
    String result = httpRequest.sendGet("http://api.ii.com.cn/goods/apprec", "page=1&size=10");


    /**
     * 创建Json文件夹
     */
    public void CreateDirectory() {

         file = new File("D:\\Json");
        boolean result = false;

        if (!file.exists()) {
            result = file.mkdir();
            if (result) {
                System.out.println("Json文件及创建成功");
            }
        } else {
            System.out.println("Json文件夹已存在");
        }

    }


    /**
     * 创建Json.txt
     */
    public void CreateFile1() {

        file1 = new File("D:\\Json\\Json.txt");
        boolean result = false;

        if (!file1.exists()) {
            try {
                result = file1.createNewFile();
                if (result) {
                    System.out.println("创建 D:\\Json\\Json.txt 成功");
                }
            } catch (Exception ex) {
            }
        } else {
            System.out.println("文本已存在");
        }
    }


    /**
     * 创建Appbean.txt
     */
    public void CreateFile2() {

        file2 = new File("D:\\Json\\Appbean.txt");
        boolean result = false;

        if (!file2.exists()) {
            try {
                result = file2.createNewFile();
                if (result) {
                    System.out.println("创建 D:\\Json\\Appbean.txt 成功");
                }
            } catch (Exception ex) {
            }
        } else {
            System.out.println("文本已存在");
        }
    }


    /**
     * 将数据（字符串）写入Json.txt
     *
     * @return
     * @throws java.io.IOException
     */
    public String writeInJsontxt() throws IOException {

        OutputStream out = new FileOutputStream("D:\\Json\\Json.txt");
        out.write(new String(result).getBytes());
        out.flush();
        out.close();

        return result;
    }

    /**
     * 将实体类写入Appben.txt
     *
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public JsonAppbean writeInAppbeantxt() throws IOException, ClassNotFoundException {

        JsonUtil jsonUtil = new JsonUtil();
        JsonAppbean jsonAppbean = jsonUtil.toPOJO(result);

        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream
                    (new FileOutputStream("D:\\Json\\Appbean.txt"));
            objectOutputStream.writeObject(jsonAppbean);
            objectOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonAppbean;
    }
}
